<template>
  <div class="pd-20">
    <el-input v-model="searchCondition"
              placeholder="请输入商品名称"
              class="w-200"
              clearable
              @clear="query" />
    <el-button type="primary"
               @click="query">查 询</el-button>
    <el-button type="primary"
               @click="configDetail(null, 'add')">新 增</el-button>
    <el-table stripe
              :data="dataList"
              border
              style="width: 100%"
              class="mt-20">
      <el-table-column align="center"
                       label="图标"
                       width="100px"
                       heitht="50px">
        <template slot-scope="scope">
          <el-image :src="scope.row.imageUrl"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name"
                       label="配置名称"
                       min-width="100">
      </el-table-column>
      <el-table-column prop="introduce"
                       label="配置介绍"
                       min-width="120">
      </el-table-column>
      <el-table-column align="center"
                       prop="createTime"
                       label="录入时间"
                       width="150"
                       :formatter="formatterDate">
      </el-table-column>
      <el-table-column label="操作"
                       width="300"
                       align="center">
        <template slot-scope="scope">
          <el-button type="primary"
                     @click="configDetail(scope.row, 'edit')">编 辑
          </el-button>
          <el-button type="info"
                     @click="configDetail(scope.row, 'detail')">配置详情
          </el-button>
          <el-button type="danger"
                     @click="configDetail(scope.row, 'del')">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <page @getList="initTable"
          :pageTotal="totals"
          ref="page"></page>
    <!-- 配置服务 -->
    <div>
      <el-dialog title="配置服务"
                 width="60%"
                 :close-on-click-modal="false"
                 :visible.sync="dialogFormVisible">
        <el-form :model="editObj"
                 :rules="configServiceRules"
                 ref="configServiceRefs">
          <el-form-item :label-width="formLabelWidth"
                        label="图标"
                        prop="imageUrl">
            <el-upload class="avatar-uploader"
                       :action="imageUploadUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload">
              <img v-if="editObj.imageUrl"
                   :src="editObj.imageUrl"
                   width="200px"
                   height="100px"
                   class="avatar">
              <i v-else
                 class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth"
                        label="图标列表"
                        prop="headPortrait">
            <el-upload class="avatar-uploader"
                       :action="imageUploadUrl"
                       list-type="picture-card"
                       :on-remove="handleRemove"
                       :on-change="handleChange"
                       :on-success="handleSuccess"
                       :before-upload="beforeAvatarUpload"
                       :file-list="photoList"
                       :class="{hide: hideUpload}">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="editObj.dialogVisible">
              <img :src="editObj.headPortrait"
                   alt=""
                   width="100px"
                   height="100px" />
            </el-dialog>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth"
                        label="名称"
                        prop="name">
            <el-input v-model="editObj.name"
                      placeholder="请填写名称"></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth"
                        label="介绍"
                        prop="introduce">
            <el-input type="textarea"
                      placeholder="请填写介绍"
                      v-model="editObj.introduce"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="saveData()">保 存</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 配置详情 -->
    <div>
      <el-dialog title="配置详情"
                 width="60%"
                 :close-on-click-modal="false"
                 :visible.sync="configDetailVisible">
        <el-form :model="detailObj">
          <el-button type="primary"
                     @click="optionItemData(null, 'add')">新 增</el-button>
          <el-table :data="detailObj.itemList"
                    style="width: 100%"
                    class="mt-20"
                    border>
            <el-table-column align="center"
                             prop="name"
                             label="配置名称"
                             min-width="100">
            </el-table-column>
            <el-table-column align="center"
                             prop="couponName"
                             label="优惠劵名称"
                             min-width="100">
            </el-table-column>
            <el-table-column align="center"
                             prop="num"
                             label="数量"
                             min-width="120">
            </el-table-column>
            <el-table-column align="center"
                             prop="createTime"
                             label="录入时间"
                             min-width="120"
                             :formatter="formatterDate">
            </el-table-column>
            <el-table-column label="操作"
                             min-width="160"
                             align="center">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="primary"
                           @click="optionItemData(scope.row, 'edit')">编辑
                </el-button>
                <el-button size="mini"
                           type="danger"
                           @click="optionItemData(scope.row, 'del')">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="configDetailVisible = false">关闭</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 配置规格 -->
    <div>
      <el-dialog title="配置规格"
                 width="50%"
                 :close-on-click-modal="false"
                 :visible.sync="configItemVisible">
        <el-form :model="sku"
                 ref="skuRefs"
                 :rules="skuRules">
          <el-form-item :label-width="formLabelWidth"
                        label="名称"
                        prop="name">
            <el-input v-model="sku.name"></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth"
                        label="优惠劵"
                        prop="couponId">
            <el-select v-model="sku.couponId"
                       placeholder="请选择优惠劵"
                       clearable>
              <el-option v-for="coupon in couponList"
                         :key="coupon.id"
                         :label="coupon.name"
                         :value="coupon.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth"
                        label="数量"
                        prop="num">
            <InputNumber v-model="sku.num"></InputNumber>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth"
                        label="介绍"
                        prop="remark">
            <el-input type="textarea"
                      v-model="sku.remark"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="configItemVisible = false">关 闭</el-button>
          <el-button @click="saveSku"
                     type="primary">保 存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import Page from '@/base/page/page'
  import { mapGetters } from 'vuex'

  export default {
    name: "goodsServiceConfigList",
    data () {
      return {
        loading: false,
        searchCondition: '',
        formLabelWidth: '120px',
        dialogFormVisible: false,
        configDetailVisible: false,
        configItemVisible: false,
        imageUploadUrl: this.api.hospitalManager.uploadImg,
        dataList: [],
        couponList: [],
        photoList: [],
        totals: 0,
        hideUpload: false,
        editObj: {
          imageUrl: null,
          name: "",
          introduce: "",
          imageList: null,
          headPortrait: []
        },
        detailObj: {},
        sku: {
          goodsServiceConfigId: null,
          name: "",
          couponId: null,
          num: 1,
          remark: ""
        },
        skuRules: {
          couponId: [
            { required: true, message: '请选择优惠劵', trigger: 'blur' }
          ]
        },
        configServiceRules: {
          imageUrl: [
            { required: true, message: '请填上传图标', trigger: ['blur', 'change'] }
          ],
          headPortrait: [
            { required: true, message: '请填上传图片', trigger: ['blur', 'change'] }
          ],
          name: [
            { required: true, message: '请填写名称', trigger: 'blur' }
          ],
          introduce: [
            { required: true, message: '请填写介绍', trigger: 'blur' }
          ],
        }
      }

    },
    created () {
      this.initTable();
    },
    methods: {
      query () {
        this.page.pageIndex = 0;
        this.initTable();
      },
      initTable () {
        let param = {
          name: this.searchCondition,
          pageSize: this.page.pageSize,
          pageIndex: this.page.pageIndex
        };
        this.post(this.api.goodsServiceConfig.getGoodsServiceConfigList, param).then((res) => {
          if (res.data.code === '200') {
            this.dataList = res.data.object;
            this.totals = res.data.totalNum;
          }
        });
      },
      // 优惠劵列表
      initCouponList () {
        this.ajax({
          type: this.api.couponList.type,
          url: this.api.couponList.url,
          data: Object.assign({}, { pageIndex: 0, pageSize: 100 }),
          success: (data) => {
            console.log(data.object);
            this.couponList = data.object;
          },
          error: (data) => {
            this.$Message.error(data.message);
          }
        })
      },
      // 配置详情
      configDetail (obj, op) {

        switch (op) {
          case 'add':
            this.dialogFormVisible = true;
            this.photoList = [];
            this.editObj = {
              imageUrl: null,
              name: '',
              introduce: '',
              imageList: null,
              headPortrait: []
            };
            break;
          case 'edit':
            this.dialogFormVisible = true;
            this.editObj = obj;
            this.editObj.headPortrait = [];
            this.photoList = [];
            if (this.editObj.imageList) {
              let images = this.editObj.imageList.split(",");
              for (let i = 0; i < images.length; i++) {
                let img = images[i];
                if (img && img.length > 0) {
                  this.editObj.headPortrait.push(img);
                  this.photoList.push({
                    url: img
                  })
                }
              }
            }
            break;
          case 'detail':
            this.configDetailVisible = true;
            this.post(this.api.goodsServiceConfig.getDetail, { id: obj.id }).then((res) => {
              if (res.data.code === '200') {
                this.detailObj = res.data.object;
              }
            });
            break;
          case 'del':
            this.$confirm('确认删除？')
              .then(_ => {
                this.post(this.api.goodsServiceConfig.del, { id: obj.id }).then((res) => {
                  if (res.data.code === '200') {
                    this.$Message.success('删除成功!');
                    this.initTable();
                  }
                });
              })
              .catch(_ => { });
            break;
        }
      },

      // 配置规格
      optionItemData (row, op) {
        switch (op) {
          case 'add':
            this.configItemVisible = true;
            if (this.$refs.skuRefs) {
              this.$refs.skuRefs.resetFields();
            }
            this.initCouponList();
            break;
          case 'edit':
            this.configItemVisible = true;
            this.sku = Object.assign({}, row);
            this.initCouponList();
            break;
          case 'del':
            this.$confirm('删除删除？')
              .then(_ => {
                this.post(this.api.goodsServiceConfig.delItem, { id: row.id }).then((res) => {
                  if (res.data.code === '200') {
                    this.$Message.info("删除成功");
                    this.configDetail(this.detailObj, 'del');
                  }
                });
              })
              .catch(_ => { });
            break;
        }
      },

      saveData () {
        this.$refs.configServiceRefs.validate((valid) => {
          if (valid) {
            if (this.editObj.headPortrait) {
              let imageList = "";
              for (let i = 0; i < this.editObj.headPortrait.length; i++) {
                imageList += this.editObj.headPortrait[i] + ",";
              }
              this.editObj.imageList = imageList;
            }
            this.post(this.api.goodsServiceConfig.uploadInfo, this.editObj).then((res) => {
              if (res.data.code === '200') {
                this.$message.success('保存成功!');
                this.initTable();
                this.dialogFormVisible = false;
              }
            });
          }
        })

      },
      // 保存规格
      saveSku () {
        this.$refs.skuRefs.validate((valid) => {
          if (valid) {
            this.sku.goodsServiceConfigId = this.detailObj.id;
            this.post(this.api.goodsServiceConfig.uploadInfoItem, this.sku).then((res) => {
              if (res.data.code === '200') {
                this.configDetail(this.detailObj, 'detail')
                this.$message.success('保存成功!');
                this.configItemVisible = false;
              }
            });
          }
        })

      },
      handleAvatarSuccess (res) {
        this.editObj.imageUrl = res.data;
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      handleRemove (file, fileList) { // 移除
        for (let i = 0; i < fileList.length; i++) {
          let f = fileList[i];
          if (file.url === f.url) {
            this.photoList.splice(i, 1);
            break;
          }
        }
        for (let i = 0; i < this.editObj.headPortrait.length; i++) {
          if (file.url === this.editObj.headPortrait[i]) {
            this.editObj.headPortrait.splice(i, 1);
            break;
          }
        }
      },
      handleChange () {
        if (this.editObj.headPortrait.length >= 8) {
          this.hideUpload = true;
        }
      },
      handleSuccess (res) {
        this.editObj.headPortrait.push(res.data);
      },
      formatterDate (row) {
        return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    computed: {
      ...mapGetters([
        'page'
      ])
    },
    components: {
      Page,
    }
  }
</script>

<style scoped>
</style>
